package com.hjy.ware.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hjy.ware.dao.PurchaseDetailDao;
import com.hjy.ware.entity.PurchaseDetailEntity;
import com.hjy.ware.service.WareSkuService;
import com.hjy.ware.vo.MergeVo;
import com.hjy.ware.vo.done.DoneItemVo;
import com.hjy.ware.vo.done.DoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.event.ItemEvent;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjy.common.utils.PageUtils;
import com.hjy.common.utils.Query;

import com.hjy.ware.dao.PurchaseDao;
import com.hjy.ware.entity.PurchaseEntity;
import com.hjy.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PreDestroy;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailDao purchaseDetailDao;

    @Autowired
    private WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils unreceiveList(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void merge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (ObjectUtil.isNull(purchaseId)) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setStatus(0);
            baseMapper.insert(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        items.forEach(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(0);
            purchaseDetailDao.updateById(purchaseDetailEntity);
        });
    }

    @Override
    public void receivedPurchase(List<Long> list) {
        // 1. 更新采购单状态为正在采购
        List<PurchaseEntity> collect = list.stream().map(item -> {
            PurchaseEntity purchaseEntity = baseMapper.selectById(item);
            return purchaseEntity;
        }).filter(item -> {
            return item.getStatus() == 0 || item.getStatus() == 1;
        }).map(item -> {
            item.setStatus(2);
            return item;
        }).collect(Collectors.toList());

        this.updateBatchById(collect);

        // 2. 更新其采购项为正在采购
        collect.forEach(purchaseEntity -> {
            Long id = purchaseEntity.getId();
            QueryWrapper<PurchaseDetailEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("purchase_id",id);
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailDao.selectList(wrapper);
            purchaseDetailEntities.forEach(purchaseDetailEntity -> {
                purchaseDetailEntity.setStatus(2);
                purchaseDetailDao.updateById(purchaseDetailEntity);
            });

        });
    }

    @Override
    @Transactional
    public void done(DoneVo doneVo) {
        // 1. 改变采购项的状态
        List<DoneItemVo> items = doneVo.getItems();
        // 采购单的状态
        boolean flag = true;
        if (CollUtil.isNotEmpty(items)) {
            for (DoneItemVo item : items) {
                // 如果有一个采购项失败, 采购单就失败
                if (item.getStatus() == 4) {
                    flag = false;
                }else {
                    PurchaseDetailEntity purchaseDetailEntity1 = purchaseDetailDao.selectById(item.getItemId());
                    wareSkuService.addStock(purchaseDetailEntity1.getSkuId(),purchaseDetailEntity1.getWareId(),purchaseDetailEntity1.getSkuNum());
                }
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setStatus(Math.toIntExact(item.getStatus()));
                purchaseDetailEntity.setId(item.getItemId());
                purchaseDetailDao.updateById(purchaseDetailEntity);
                // 3. 录入库存 wms_ware_sku
                // 首先查出对应的 PurchaseDetailEntity
                PurchaseDetailEntity purchaseDetailEntity1 = purchaseDetailDao.selectById(item.getItemId());
                wareSkuService.addStock(purchaseDetailEntity1.getSkuId(),purchaseDetailEntity1.getWareId(),purchaseDetailEntity1.getSkuNum());
            }
        }
        // 2. 改变采购单的状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(doneVo.getId());
        if (flag) {
            purchaseEntity.setStatus(3);
        }else {
            purchaseEntity.setStatus(4);
        }
        baseMapper.updateById(purchaseEntity);

    }

}